package com.etl.dataflow.scheduler.communication.controller;

import com.etl.dataflow.common.entity.ExecutorInfo;
import com.etl.dataflow.common.response.R;
import com.etl.dataflow.scheduler.communication.service.SchedulerService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

/**
 * 暴露给执行器的接口
 *
 * @author dx
 * @since 2022/4/20
 */
@RestController("/")
@Validated
public class SchedulerController {

    @Resource
    private SchedulerService schedulerService;

    /**
     * 注册执行器
     *
     * @param executorInfo 执行器信息
     * @return R
     */
    @PostMapping("/register")
    public R register(@RequestBody @Validated ExecutorInfo executorInfo) {
        return schedulerService.register(executorInfo);
    }

    /**
     * 更新任务状态为正常结束
     *
     * @param uuid   执行器uuid
     * @param taskId 任务id
     * @return R
     */
    @GetMapping("/state/finished/{uuid}/{taskId}/{taskRecordId}")
    public R updateTaskStateToFinished(@NotBlank @Valid @PathVariable String uuid,
                                       @NotBlank @Valid @PathVariable String taskId,
                                       @NotBlank @Valid @PathVariable String taskRecordId) {
        return schedulerService.updateTaskStateToFinished(uuid, taskId, taskRecordId);
    }

    /**
     * 更新任务状态为执行出错
     *
     * @param uuid   执行器uuid
     * @param taskId 任务id
     * @param taskRecordId 任务记录id
     * @return R
     */
    @PostMapping("/state/error/{uuid}/{taskId}/{taskRecordId}")
    public R updateTaskStateToError(@NotBlank @Valid @PathVariable String uuid,
                                    @NotBlank @Valid @PathVariable String taskId,
                                    @NotBlank @Valid @PathVariable String taskRecordId,
                                    @RequestParam("errorMsg") @NotBlank String errorMsg) {
        return schedulerService.updateTaskStateToError(uuid, taskId, taskRecordId, errorMsg);
    }

    /**
     * 更新任务状态为超时
     *
     * @param uuid         执行器uuid
     * @param taskId       任务id
     * @param taskRecordId 任务记录id
     * @return R
     */
    @PostMapping("/state/timeout/{uuid}/{taskId}/{taskRecordId}")
    public R updateTaskStateToTimeout(@NotBlank @Valid @PathVariable String uuid,
                                      @NotBlank @Valid @PathVariable String taskId,
                                      @NotBlank @Valid @PathVariable String taskRecordId) {
        return schedulerService.updateTaskStateToTimeout(uuid, taskId, taskRecordId);
    }
}
